import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import * as path from 'path';
import autoprefixer from 'autoprefixer';
import tailwindcss from 'tailwindcss';
import { VitePluginExternal } from './plugins/vite-plugin-external';
import { VitePluginImportDemand } from './plugins/vite-plugin-import-demand';

const prefix = `monaco-editor/esm/vs`;
const ENV_DIR = path.join(__dirname, 'src/envs');

// function plugins(): PluginOption {
//   return {
//     name: 'my-plugin',
//     enforce: 'pre',
//     resolveId(source) {
//       console.log(source);
//       // return source;
//     },
//     transform(code, id) {
//       let _code;
//       if (id.includes('monaco-editor')) {
//         console.log(code, 'code');
//         _code = code.replace(
//           'createScript("".concat(state.config.paths.vs, "/loader.js"))',
//           `createScript(false);console.log(createScript)`,
//         );
//       } else {
//         _code = code;
//       }
//       return {
//         code: _code,
//         map: null,
//         id: id,
//       };
//     },
//   };
// }

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, ENV_DIR, '');
  return {
    plugins: [react(), VitePluginExternal(), VitePluginImportDemand()],
    resolve: {
      alias: [
        {
          find: '@',
          replacement: path.resolve(__dirname, 'src'),
        },
      ],
    },
    build: {
      target: 'modules',
      outDir: 'dist',
      assetsDir: 'assets',
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        output: {
          manualChunks: {
            jsonWorker: [`${prefix}/language/json/json.worker`],
            cssWorker: [`${prefix}/language/css/css.worker`],
            htmlWorker: [`${prefix}/language/html/html.worker`],
            tsWorker: [`${prefix}/language/typescript/ts.worker`],
            editorWorker: [`${prefix}/editor/editor.worker`],
          },
        },
      },
    },
    server: {
      host: 'localhost',
      port: 3333,
      open: true, // 自动打开浏览器
      strictPort: false, // 端口被占用的话换一个
      cors: true, // 允许跨域
      proxy: {
        '/api': {
          target: env.VITE_APP_PROXYURL,
          changeOrigin: true, // 接口跨域
          secure: true, // 若启用https服务需要配置
        },
        '/aitutor': {
          target: env.VITE_APP_PROXYURL,
          changeOrigin: true, // 接口跨域
          secure: true, // 若启用https服务需要配置
          ws: true,
        },
      },
    },
    envDir: ENV_DIR,
    css: {
      postcss: { plugins: [autoprefixer(), tailwindcss] },
      preprocessorOptions: {
        less: {
          math: 'always',
        },
      },
    },
  };
});
